package com.Projects.Exam.demo4;

import java.util.Arrays;
import java.util.Objects;

public class MyArrayList<E> {
	private final int DEFAULT_CAPACITY = 10;
	private Object[] elementData = {};
	private int size;
	
	// add方法
	public boolean add(E e) {
		if (size == elementData.length) {
			Expansion();
		}
		elementData[size++] = e;
		return true;
	}
	
	
	// 获取
	public E get(int index) {
		isIndex(index);
		return (E) elementData[index];
	}
	
	// 删除
	public E remove(int index) {
		isIndex(index);
		E e = (E) elementData[index];
//		if (index == size || index == size - 1) {
//			elementData[index] = null;
//			return e;
//		} else {
//			elementData[index] = elementData[size - 1];
//      elementData[--size] = null;
//			return e;
//		}
		int i = size - index - 1;
		if (i != 0) {
			System.arraycopy(elementData, index + 1, elementData, index, i);
		}
		elementData[--size] = null;
		return e;
	}
	
	
	// foreach
	public E forEach(Myinterface<E> acction) {
		Objects.requireNonNull(acction);
		for (int i = 0; i < size; i++) {
			acction.accept((E) elementData[i]);
		}
		
		return (E) elementData[size];
	}
	
	// 长度
	public int size() {
		return size;
	}
	
	@Override
	public String toString() {
		StringBuilder str = new StringBuilder();
		str.append("[");
		for (int i = 0; i < size; i++) {
			str.append(elementData[i]).append(i == size - 1 ? "" : ",");
		}
		str.append("]");
		return str.toString();
	}
	
	// 判断下标
	private void isIndex(int index) {
		if (index == 0 || index > size) {
			throw new IndexOutOfBoundsException("index " + index + " out of bounds");
		}
	}
	
	
	// 扩容位置
	private void Expansion() {
		if (size == 0) {
			elementData = new Object[DEFAULT_CAPACITY];
		} else {
			elementData = Arrays.copyOf(elementData, elementData.length + elementData.length >> 1);
		}
	}
	
}
